import os
import platform
import logging
import config

"""
执行这个init脚本，主要完成以下几个功能
1. 自动下载所有cve数据并解压放置到data/CVEXML目录下
2. 对于刚刚下载的cve数据执行解析，放置到data/cvedata.pkl文件中
3. 下载cve的更新修改内容，并回填到data/cvedata.pkl文件中
4. 若是win操作系统，当不存在FuncParser-opt.exe时下载辅助解析器
"""

try:
    import tools.cvedatagen.cveXmlDownloader as Downloader
except ImportError:
    import cveXmlDownloader as Downloader
try:
    import tools.cvedatagen.cveXmlParser as Parser
except ImportError:
    import cveXmlParser as Parser
try:
    import tools.cvedatagen.cveXmlUpdater as Updater
except ImportError:
    import cveXmlUpdater as Updater

import tools.cvedatagen.common as common


def main():
    logging.info("Making directories...")
    dataDir = os.path.join(config.ROOT_PATH, "data", "repolists")
    if os.path.exists(dataDir) is False:
        os.makedirs(dataDir)
    diffDir = os.path.join(config.ROOT_PATH, "diff")
    if os.path.exists(diffDir) is False:
        os.makedirs(diffDir)
    vulDir = os.path.join(config.ROOT_PATH, "vul")
    if os.path.exists(vulDir) is False:
        os.makedirs(vulDir)
    hidxDir = os.path.join(config.ROOT_PATH, "hidx")
    if os.path.exists(hidxDir) is False:
        os.makedirs(hidxDir)


    logging.info("Running CVE data generator...")

    os.chdir(os.path.join(config.ROOT_PATH, "data"))
    if "cvedata.pkl" not in os.listdir("./"):
        logging.info("cvedata.pkl not found. Proceeding to download..")
        logging.info("[+] cveXmlDownloader")
        Downloader.process()    # 下载并解压

        logging.info("[+] cveXmlParser")
        Parser.process()    # 解析到cvedata.pkl文件中
    else:
        logging.info("cvedata.pkl found. Omitting download..")

    logging.info("[+] cveXmlUpdater")
    Updater.process()

    os.chdir(config.ROOT_PATH)
    logging.info("cvedata.pkl is now up-to-date.\n")

    if config.os_is_windows():  # Windows
        if os.path.exists(os.path.join(config.ROOT_PATH, "tools", "FuncParser-opt.exe")) is False:
            logging.info("Downloading function parser for Windows...")
            os.chdir(os.path.join(config.ROOT_PATH, "tools"))
            # 对于这个url，国内翻墙的用户可以手动前往https://gitee.com/ChiZhung/func-parser/blob/master/FuncParser-opt.zip下载
            # 然后解压到目标目录下
            url = "https://github.com/squizz617/FuncParser-opt/raw/master/FuncParser-opt.zip"
            fileName = "FuncParser-opt.zip"
            common.download_url(url, fileName)
            common.unzip(fileName)
            os.remove(fileName)

    logging.info("*** Please modify config.py before running scripts in src/ ***")


if __name__ == '__main__':
    config.conf_log()
    main()
